import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:wanke/block_history.dart';
import 'function.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class BlockPage extends StatefulWidget {
  BlockPage(this.mainColor, {this.addr});
  final String addr;
  final Color mainColor;
  @override
  _BlockPageState createState() => new _BlockPageState(addr);
}

class _BlockPageState extends State<BlockPage> {
  String balance = "0";
  List blockArr = [];
  int count = 0;
  bool loading = true;
  String addr;
  String barcode = "";
  RefreshController _refreshController = new RefreshController();
  _BlockPageState(this.addr) {
    initBlock();
  }
  initBlock() async {
    blockInfo(true);
  }

  blockInfo(bool up) async {
    if (this.addr == null) {
      return false;
    }
    if (this.addr.indexOf("0x") == -1 || this.addr.length != 42) {
      toast("钱包地址有误");
      return false;
    }

    var blockData;
    if (up == true) {
      this.blockArr = [];
      this.count = 0;
      this.balance = "0";
      this.loading = true;
      if (mounted) {
        setState(() {});
      }
    }
    if (this.blockArr.length == 0) {
      blockData = await getBlockInfo(this.addr, 0);
      var balanceData = await getBlockBalance(this.addr);
      print(balanceData);
      this.balance = convertBlock(balanceData['result']);
    } else {
      blockData =
          await getBlockInfo(this.addr, this.blockArr.last['timestamp'] - 1);
    }
    this.count = blockData['total'] + this.blockArr.length;
    addBlock(addr, this.balance, count);
    this.blockArr.addAll(blockData['result']);
    this.loading = false;
    if (blockData['total'] <= 20) {
      this.loading = false;
      _refreshController.sendBack(false, RefreshStatus.noMore);
      setState(() {});
      return false;
    }
    //this.balance = double.parse(drawData['totalOutcome']);
    if (up == false) {
      print(up);
      _refreshController.sendBack(false, RefreshStatus.idle);
    }
    setState(() {});
  }

  Widget _buildTiles(Map block) {
    return new Column(
      children: <Widget>[
        new ListTile(
          onTap: () {
            showDialog<Null>(
              context: context,
              builder: (context) {
                return new AlertDialog(
                  title: new Text("钱包地址"),
                  content: new Text(block['tradeAccount']),
                  actions: <Widget>[
                    new FlatButton(
                      onPressed: () {
                        this.addr = block['tradeAccount'];
                        Navigator.of(context).pop();
                        blockInfo(true);
                      },
                      child: new Text(
                        '查此地址',
                      ),
                    ),
                    new FlatButton(
                      onPressed: () {
                        Navigator.pop(context);
                      },
                      child: new Text(
                        '取消',
                      ),
                    ),
                  ],
                );
              },
            );
          },
          title: new Row(
            children: <Widget>[
              new Container(
                padding: EdgeInsets.only(right: 5.0, left: 5.0),
                margin: EdgeInsets.only(right: 5.0),
                decoration: new BoxDecoration(
                    border: new Border.all(
                      color: widget.mainColor,
                    ),
                    borderRadius:
                        new BorderRadius.all(new Radius.circular(5.0))),
                child: new Text(
                  (block['type'] == 0 || block['type'] == 1) ? "转账" : "合约",
                  style: new TextStyle(fontSize: 12.0, color: widget.mainColor),
                  textAlign: TextAlign.center,
                ),
              ),
              new Text(
                ("0x****" +
                    block['tradeAccount']
                        .substring(block['tradeAccount'].length - 6)),
                style: new TextStyle(fontSize: 16.0, color: Colors.black),
              ),
            ],
          ),
          subtitle: new Text(convertTime(block['timestamp'])),
          trailing: new Column(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: <Widget>[
              new Text(
                ((block['type'] == 0 || block['type'] == 2) ? "-" : "+") +
                    convertBlock(block['amount']),
                style: new TextStyle(
                  color: block['type'] == 0 ? Colors.green : Colors.red,
                  fontSize: 22.0,
                ),
              ),
              new Text(
                "手续费:" + convertBlock(block['cost']),
              )
            ],
          ),
        ),
        Divider(height: 1.0),
      ],
    );
  }

  Widget _pullupBuilder(context, mode) {
    return new ClassicIndicator(
      mode: mode,
      idleText: "上拉加载更多",
      completeText: "加载完成",
      refreshingText: "加载中…",
      releaseText: "松手开始加载",
      noMoreIcon: new Icon(Icons.close),
      noDataText: "到底了",
      idleIcon: new Icon(Icons.arrow_upward),
      refreshingIcon: const CupertinoActivityIndicator(),
      completeIcon: const Icon(Icons.done, size: 32.0, color: Colors.green),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: new CupertinoNavigationBar(
        actionsForegroundColor: Colors.white,
        backgroundColor: widget.mainColor,
        border: new Border(bottom: BorderSide.none),
        middle: new Text(
          "区块查询",
          style: new TextStyle(
            color: Colors.white,
            fontWeight: FontWeight.normal,
          ),
        ),
        trailing: new CupertinoButton(
          padding: EdgeInsets.all(0.0),
          minSize: 22.0,
          child: new Icon(
            Icons.history,
            color: Colors.white,
            size: 20.0,
          ),
          onPressed: () {
            Navigator.of(context).push(
              new CupertinoPageRoute(builder: (context) {
                return new BlockHistory(widget.mainColor);
              }),
            ).then((value) {
              if (value != null) {
                this.addr = value;
                blockInfo(true);
              }
            });
          },
        ),
      ),
      body: new Container(
        child: new Column(
          children: <Widget>[
            new TextField(
              controller: new TextEditingController(text: this.addr ?? ""),
              onChanged: (value) => addr = value,
              style: new TextStyle(
                fontSize: 15.0,
                color: Colors.white,
              ),
              decoration: new InputDecoration(
                filled: true,
                fillColor: widget.mainColor,
                border: InputBorder.none,
                hintText: "请输入钱包地址",
                hintStyle: new TextStyle(color: Colors.white70),
                prefixIcon: new IconButton(
                  icon: new ImageIcon(
                    AssetImage("images/qrcode.png"),
                    color: Colors.white,
                    size: 22.0,
                  ),
                  onPressed: () async {
                    var scanAddr = await scan();
//                      var scanAddr = await new QRCodeReader()
//                          .setAutoFocusIntervalInMs(200)
//                          .setForceAutoFocus(true)
//                          .setTorchEnabled(true)
//                          .setHandlePermissions(true)
//                          .setExecuteAfterPermissionGranted(true)
//                          .scan();
                    if (scanAddr == null) {
                      return;
                    }
                    if (scanAddr.indexOf("0x") == -1) {
                      toast("钱包地址有误");
                      return;
                    }
                    this.addr = scanAddr;
                    setState(() {});
                    blockInfo(true);
                  },
                ),
                suffixIcon: new IconButton(
                  icon: new Icon(
                    Icons.search,
                    color: Colors.white,
                    size: 22.0,
                  ),
                  onPressed: () {
                    blockInfo(true);
                  },
                ),
              ),
            ),
            new Container(
              color: widget.mainColor,
              padding: EdgeInsets.all(15.0),
              child: new Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: <Widget>[
                  new Text(
                    "账户余额：${this.balance}",
                    style: new TextStyle(color: Colors.white),
                  ),
                  new Text(
                    "交易次数：" + this.count.toString(),
                    style: new TextStyle(color: Colors.white),
                  )
                ],
              ),
            ),
            new Expanded(
              child: this.loading && this.addr != null
                  ? new Center(child: new CircularProgressIndicator())
                  : this.count > 0
                  ? new SmartRefresher(
                enablePullDown: false,
                enablePullUp: true,
                onRefresh: blockInfo,
                footerBuilder: _pullupBuilder,
                controller: _refreshController,
                child: new ListView.builder(
                  itemCount: blockArr.length,
                  itemBuilder: (context, i) =>
                      _buildTiles(blockArr[i]),
                ),
              )
                  : new Center(
                child: new Container(
                  width: 200.0,
                  height: 200.0,
                  child: new Column(
                    children: <Widget>[
                      new Text(
                        this.addr == null ? "请输入钱包地址" : "暂无区块信息",
                        style: new TextStyle(fontSize: 22.0),
                      ),
                      new FlatButton(
                          onPressed: () {
                            Navigator.of(context).pop();
                          },
                          child: new Text("返回")),
                    ],
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
